package code;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/**
 * @author
 * 
 * This class is the main class and it handles the interaction with user
 */
public class TreeDriver {
	
	public static void main(String args[]) throws IOException {
		
		Tree tree = null;
		while (true) {
			
			System.out.println();
			System.out.println(
					"L - Load a Tree.\nH - Begin a Help Session.\nT - Traverse the Tree in preorder.\nQ - Quit");
			System.out.print("Choice> ");
			Scanner scanner = new Scanner(System.in);
			String cmd = scanner.nextLine();
			if (cmd.equalsIgnoreCase("L")) {
				System.out.println();
				System.out.print("Enter the file name> ");
				String name = scanner.nextLine();
				System.out.println();
				BufferedReader reader = new BufferedReader(new FileReader(new File(name)));
				String rootLabel = reader.readLine().trim();
				String rootPromot = reader.readLine().trim();
				String rootMsg = reader.readLine().trim();
				TreeNode root = new TreeNode();
				root.setLabel(rootLabel);
				root.setPrompt(rootPromot);
				root.setMessage(rootMsg);
				tree = new Tree(root);
				String line = "";
				while((line = reader.readLine())!=null){
					line = line.trim();
					String s[] = line.split(" ");
					String pLabel = s[0];
					int childNum = Integer.parseInt(s[1]);
					for(int i=0;i<childNum;i++){
						String label = reader.readLine().trim();
						String prompt = reader.readLine().trim();
						String message = reader.readLine().trim();
						tree.addNode(label, prompt, message, pLabel);
					}
				}
				System.out.println("Tree created successfully!");
				reader.close();
			}
			if (cmd.equalsIgnoreCase("H")) {
				if(tree == null){
					System.out.println("Load a Tree first!");
				}else{
					tree.beginSession();
				}
			}
			if (cmd.equalsIgnoreCase("T")) {
				if(tree == null){
					System.out.println("Load a Tree first!");
				}else{
					tree.preOrder();
				}
			}
			if (cmd.equalsIgnoreCase("Q")) {
				System.out.println();
				System.out.println("Thank you for using our automated help services!");
				break;
			}
		}
		
	}
}
